namespace EyeOpen.Logging
{
	using System;
	using System.Collections.Generic;

	public static class DisposableExtensions
	{
		public static void Using<T>(this T disposable, Action<T> action)
			where T : IDisposable
		{
			try
			{
				action(disposable);
			}
			finally
			{
				if (!EqualityComparer<T>.Default.Equals(default(T)))
				{
					disposable.Dispose();
				}
			}
		}

		public static void UsingWithLog<T>(this T disposable, Action<T> action, bool throwException = false)
			where T : IDisposable
		{
			try
			{
				action(disposable);
			}
			catch (Exception ex)
			{
				DependencyResolver
					.Resolve<ILogger>()
					.Debug(ex);

				if (throwException)
				{
					throw;
				}
			}
			finally
			{
				if (!EqualityComparer<T>.Default.Equals(default(T)))
				{
					disposable.Dispose();
				}
			}
		}
	}
}